package com.wit.witmg.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wit.witmg.entity.TProdstock;
import com.wit.witmg.entity.TPurchase;
import com.wit.witmg.entity.TPurchcontr;
import com.wit.witmg.entity.TPurchinput;
import com.wit.witmg.mapper.TPurchinputMapper;
import com.wit.witmg.service.ITProdstockService;
import com.wit.witmg.service.ITPurchaseService;
import com.wit.witmg.service.ITPurchcontrService;
import com.wit.witmg.service.ITPurchinputService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wit.witmg.util.ErrorCode;
import com.wit.witmg.util.JsonResult;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author bob
 * @since 2025-01-15
 */
@Service
@RequiredArgsConstructor
public class TPurchinputServiceImpl extends ServiceImpl<TPurchinputMapper, TPurchinput> implements ITPurchinputService {
    final ITProdstockService prodstockService;
    final ITPurchcontrService contrService;
    final ITPurchaseService purchaseService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object add(HttpServletRequest request, String json) {
//        备注：入库金额为去税后金额；提交后同时根据bn修改物料库存表t_prodStock的数量qt（+inqt）和金额amount（+amount）；
//        若物料库存表不存在该bn,则增加一条数据;根据pid=》id把报价表t_purchContr的数量inqt（+inqt）；
//        并判断若相加后的inqt>=pqt则吧stat改为5；根据报价表的pid=》id把采购计划表t_purchase的数量inqt（+inqt）；
//        并判断若相加后的inqt>=pqt则吧stat改为5；

        TPurchinput t= JSON.parseObject(json,TPurchinput.class);
        t.setDate(new Date());
        boolean bl= save(t);
        if(!bl){
            return JsonResult.error(ErrorCode.ERR_504);
        }
        if(!t.getBn().isEmpty()){
            //修改物料库存表数量
            QueryWrapper<TProdstock> qw=new QueryWrapper<>();
            qw.eq("bn",t.getBn());
            qw.last("limit 1");
            TProdstock tp=prodstockService.getOne(qw);
            if(tp==null){
                tp= JSON.parseObject(json,TProdstock.class);
                tp.setQt(t.getInqt());
                tp.setAmount(t.getAmount());
                tp.setPqt(0.0);
                tp.setDate(new Date());
                bl= prodstockService.save(tp);
                if(!bl){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//回滚
                    return JsonResult.error(ErrorCode.ERR_504);
                }
            }else{
                tp.setQt(tp.getQt()+t.getInqt());
                tp.setAmount(tp.getAmount()+t.getAmount());
                bl= prodstockService.updateById(tp);
                if(!bl){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//回滚
                    return JsonResult.error(ErrorCode.ERR_504);
                }
            }

        }
        if(t.getPid()!=null){
            TPurchcontr tp=contrService.getById(t.getPid());
            if(tp!=null){
                tp.setInqt(tp.getInqt()+t.getInqt());
                if(tp.getInqt()>=tp.getPqt()){
                    tp.setStat(5);
                }
                bl= contrService.updateById(tp);
                if(!bl){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//回滚
                    return JsonResult.error(ErrorCode.ERR_504);
                }
                TPurchase tpe=purchaseService.getById(tp.getPid());
                if(tpe!=null){
                    tpe.setInqt(tpe.getInqt()+t.getInqt());
                    if(tpe.getInqt()>=tpe.getPqt()){
                        tpe.setStat(5);
                    }
                    bl= purchaseService.updateById(tpe);
                    if(!bl){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//回滚
                        return JsonResult.error(ErrorCode.ERR_504);
                    }
                }

            }
        }

        return JsonResult.success(t);
    }


    @Override
    public Object get(HttpServletRequest request, Integer id, Integer supid, String size, String bn) {
        //参数：bn或size或supid返回数组；id返回单条数据。
        QueryWrapper<TPurchinput> qw=new QueryWrapper<>();
        if(id!=null){
            qw.eq("id",id);
            qw.last("limit 1");
            return JsonResult.success(getOne(qw));
        }
        if(supid!=null){
            qw.eq("supid",supid);
            return JsonResult.success(list(qw));
        }
        if(size!=null){
            qw.like("size",size);
            return JsonResult.success(list(qw));
        }
        if(bn!=null){
            qw.like("bn",bn);
            return JsonResult.success(list(qw));
        }
        return JsonResult.error(ErrorCode.ERR_200);
    }

}
